package com.yutian.socketbio.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author zhoulei7
 * @create 2020-09-14
 **/
public class Client {
    private static Logger log = LoggerFactory.getLogger(Client.class);

    public static void connectToServer(String ServerIp, int ServerPort, String greet) {
        //创建客户端socket建立连接，指定服务器地址和端口
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            socket = new Socket(ServerIp,ServerPort);
            //获取输出流，向服务器端发送信息
            outputStream = socket.getOutputStream();//字节输出流
            PrintWriter pw = new PrintWriter(outputStream); //将输出流包装为打印流
            log.info("我是客户端，向服务器致发送请求："+greet);
            pw.write(greet);
            pw.flush();
            // 只要关闭Socket的InputStream或OutputStream其中任何一个，就关闭了Socket，这是不好的关闭方法。正确的方法应该是ShutdownInput/ShutdownOutput。
            socket.shutdownOutput();

            //获取输入流，读取服务器端的响应
            inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String info = null;
            while((info = br.readLine()) != null){
                log.info("我是客户端，服务器回复了我："+info);
            }
            // 只要关闭Socket的InputStream或OutputStream其中任何一个，就关闭了Socket，这是不好的关闭方法。正确的方法应该是ShutdownInput/ShutdownOutput。
            socket.shutdownInput();

        } catch (IOException e) {
            log.error(e.getMessage(), e);

        } finally {
            //关闭资源
            /*if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if(null != outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }*/
            // Socket关闭之后，自然和它相关的输入输出流都会被它关闭
            if(null != socket){
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
